package daemon;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

import common.*;
/**
 * Represents a library of packages, which can be accessed by a simple TCP protocol.
 * Creates a new thread which awaits connections on a specified port.
 */
public class PackageServer implements Runnable {
	
	/**
	 *A mapping from a package id to package name string.  
	 */
	private HashMap<PackageID, String> packages = new HashMap<PackageID, String>();
	private volatile int port;
	private String packagePath;
	private ServerSocket listener;
	public PackageServer(){
		
	}
	
	/**
	 * Attempts to start functioning and perhaps throws an error.
	 * Server accepts connections in while loop and handles them in separate threads.
	 * @param packagePath
	 * @param port
	 */
	public PackageServer(int port, String packagePath) {
		this.port = port;
		this.packagePath = packagePath;
		System.out.println("creatin' socket at " + port);
    	try {
			listener = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
    	this.port = listener.getLocalPort();
		new Thread(this).start();
	}
	
	public int getPort()  { 
		return port;
	}
	
	public void run(){
		try{
	    	while (true) {
	    		Socket temporarySocket = listener.accept();
	    		PackageServerConnection runner = new PackageServerConnection(packagePath,temporarySocket);
	    		new Thread(runner).start();
	    	}
	    }
	    catch (java.lang.Exception ex) {
	      ex.printStackTrace(System.out);
	    }    
	}
	
	/**
	 * Puts a file into register.
	 * @param packageID package identification 
	 * @param path sting corresponding to package path
	 */
	public void registerPackage(PackageID packageID, String path) {
		packages.put(packageID, path);
	}
	
	/**
	 * Function implements deleting a package from a register.
	 * @param packageID
	 */
	public void unregisterPackage(PackageID packageID) {
		packages.remove(packageID);
	}
	
}
